﻿using System;
using System.Linq;
using System.Timers;
using System.Diagnostics;
using System.Runtime.InteropServices; //Use it to getActiveObject
using System.Text.RegularExpressions;


namespace CSharpAutomation
{
    internal class Program
    {
        private static Timer _timer;
        private static WordAutomate _wordApp;
        private static string _wordName;

        #region Config
        const int INTERVAL = 60000; // 60 secs
        #endregion

        static void Main()
        {
            _wordApp = new WordAutomate();
            Object avaiWordApp = GetApp();
            // if an app available
            if (avaiWordApp != null)
            {
                _wordApp.GetApp(avaiWordApp); // Get App from current running apps
                if (!_wordApp.HasDoc())
                    _wordApp.NewDoc(); // Create new doc, if available App doesn't have any doc
            }
            else
            {
                _wordApp.New(); // Create new app
                _wordApp.NewDoc();
            }
            _wordName = _wordApp.GetName(); // Get name of wordDoc

            #region Check if _wordName was a documenw which named by this program before
            Regex rgStandardName = new Regex(@"\w+\[\d{1,2}-\d{1,}-\d{1,4}-\d{1,2}-\d{1,2}-\d{1,2}\]\.(doc?x)");
            if (rgStandardName.IsMatch(_wordName)) { // If the word document has format name, we'll keep it 
                for (int i = 0; i < _wordName.Count(); i++) {
                    if (_wordName[i] == '[') {
                        _wordName = _wordName.Remove(i, _wordName.Count() - i); // Remove from [ character to end, we'll add new name later
                        break;
                    }
                }
            }

            #endregion

            // Set timer to save document every INTERVAL of time
            // INTERVAL is declared above
            _timer = new Timer();
            _timer.Elapsed += TimerElapsed;
            _timer.Interval = INTERVAL;
            _timer.Start();

            Console.WriteLine("Press the Enter key to exit the program.");
            Console.ReadLine();
        }

        // Check if a WordApp available, return Word Object if avai, else null
        static Object GetApp()
        {
            Object obj;
            Process[] proc;
            proc = Process.GetProcessesByName("WINWORD");
            if (proc.Count() != 0)
            {
                obj = Marshal.GetActiveObject("Word.Application");
                return obj;
            }
            return null;
        }
        // if time elapsed
        // fileName format : name[day-month-year-hour-minue-second].docx
        private static void TimerElapsed(object source, ElapsedEventArgs e)
        {
            string time = e.SignalTime.Day + "-"
                          + e.SignalTime.Month + "-"
                          + e.SignalTime.Year + "-"
                          + e.SignalTime.Hour + "-"
                          + e.SignalTime.Minute + "-"
                          + e.SignalTime.Second;

            string fileName = _wordName + "[" + time + "]" + ".docx";
            _wordApp.SaveAs(fileName);
            Console.WriteLine("Saved {0}", fileName);
        }
    }
}
